package com.sys.user.controller.adminuser;


import com.chezhujie.www.domain.Czjbusiness;
import com.chezhujie.www.service.CzjbusinessService;
import com.chezhujie.www.service.CzjcommodityService;
import com.sys.core.page.Pagination;
import com.sys.core.utils.ConvertObj;
import com.sys.core.utils.DecriptTest;
import com.sys.core.utils.UUIDUtils;
import com.sys.user.base.controller.BaseController;
import com.sys.user.domain.Xyrole;
import com.sys.user.domain.Xyuser;
import com.sys.user.domain.Xyuserrole;
import com.sys.user.service.XyroleService;
import com.sys.user.service.XyuserService;
import com.sys.user.service.XyuserroleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 *   用户
 * Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/xyuser")
public class XyuserController extends BaseController<Xyuser> {
    @Autowired
    private XyuserService xyuserService;
    @Autowired
    private CzjbusinessService czjbusinessService;
    @Autowired
    private XyuserroleService xyuserroleService;
    @Autowired
    private XyroleService xyroleService;
    @Autowired
    private CzjcommodityService czjcommodityService;

    /** 列表 **/
    @RequestMapping("/list.do")
    public String list(Integer pageNo, Integer pageSize, Xyuser xyuser, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(xyuser,req,model);
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(xyuser);
            Pagination pagination = xyuserService.list(pageNo.intValue(), pageSize.intValue(), params, model);
            model.addAttribute("pagination", pagination);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取用户列表失败!"+e.getMessage());
        }
        model.addAttribute("entity", xyuser);
        return "xyuser/list";
    }
    /**
    * api接口用户列表
    * @param pageNo
    * @param pageSize
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiList.jn")
    public void apiList(Integer pageNo, Integer pageSize, Xyuser xyuser,
        HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(xyuser);
            Pagination pagination = xyuserService.apilist(pageNo.intValue(), pageSize.intValue(), params, model);
            jsonResult(1,"","",pagination,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","获取用户列表失败!"+e,"",resp);
        }

    }
    /**
    * api接口用户详情
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiDetail.jn")
    public void apiDetail(HttpServletRequest req, HttpServletResponse resp,
    ModelMap model) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<String> enumeration = req.getParameterNames();
        if(enumeration.hasMoreElements()){
            String next = enumeration.nextElement();
            params.put(next, req.getParameter(next));
        }

        try {
            Map<String,Object> result = xyuserService.getApiDetail(params);
            jsonResult(1,"","",result,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99","获取用户详情失败!"+e,"",resp);
        }

    }
    /** api测试页面 **/
    @RequestMapping("/apiTest.do")
    public String apiList(HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        model.addAttribute("entity",new HashMap<String,Object>());
        return "xyuser/apiTest";

    }

    /** 保存 **/
    @RequestMapping("/save.do")
    public String save(Xyuser xyuser,
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {
            //添加权限
            String[] roleIds = req.getParameterValues("roleId");



            if(xyuser.getPassword()!=null){
                xyuser.setPassword(DecriptTest.SHA1(xyuser.getPassword()));
            }
            if(StringUtils.isNotBlank(xyuser.getUserId())){
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("userId",xyuser.getUserId());
                map.put("nickname",xyuser.getNickname());
                czjbusinessService.updateUnameByUserId(map);
                xyuserService.update(xyuser);
                Integer hasBusiness =0;//需要商家，或者需要创建商家 0不需要 1需要
                //用户之前是否存在商家
                if(roleIds!=null&&roleIds.length!=0){
                    List<Xyrole> listxyrole = xyroleService.queryByIds(Arrays.asList(roleIds));
                    for (Xyrole xyrole : listxyrole) {
                        if("商家".equals(xyrole.getName())){
                            hasBusiness=1;//存在
                        }
                    }
                }

                Czjbusiness business = czjbusinessService.queryByUserId(xyuser.getUserId());
                if(business==null&&hasBusiness==1){//之前没有，现在有了
                    //商家创建
                    Czjbusiness busin = new Czjbusiness();
                    String phone=req.getParameter("phone");
                    busin.setUsername(xyuser.getUserId());
                    busin.setId(UUIDUtils.getUUID());
                    if(null!=xyuser.getNickname()){
                        busin.setBusinessName(xyuser.getNickname());
                    }
                    busin.setPhone(phone);
                    czjbusinessService.insert(busin);
                }else if(business==null&&hasBusiness==0){//之前没有，现在也没有

                }else if(business!=null&&hasBusiness==0){//之前有了，现在没有
                    czjbusinessService.update(business);//删除商家，假删
                    czjcommodityService.updateDelByBusinessId(business.getId(),1);//把商家所有商品给下架了
                }else if(business!=null&&hasBusiness==1){//之前有了，现在也有
                    business.setPhone(req.getParameter("phone"));
                    business.setDelFlag(0);
                    czjbusinessService.update(business);
                }




            }else{
                Xyuser user = xyuserService.getByUsername(xyuser.getUsername());
                if(user!=null){
                    model.addAttribute("failed", "用户名已存在！");
                    return "redirect:list.do";
                }
                xyuser.setUserId(UUIDUtils.getUUID());
                xyuserService.insert(xyuser);
                Integer iscreate =0;
                if(roleIds!=null&&roleIds.length!=0){
                    List<Xyrole> listxyrole = xyroleService.queryByIds(Arrays.asList(roleIds));
                    for (Xyrole xyrole : listxyrole) {
                        if("商家".equals(xyrole.getName())){
                            iscreate=1;
                        }
                    }
                }

                if(iscreate!=null&&iscreate==1){

                    //商家创建
                    Czjbusiness busin = new Czjbusiness();
                    String phone=req.getParameter("phone");
                    busin.setUsername(xyuser.getUserId());
                    busin.setId(UUIDUtils.getUUID());
                    if(null!=xyuser.getNickname()){
                        busin.setBusinessName(xyuser.getNickname());
                    }
                    busin.setPhone(phone);
                    czjbusinessService.insert(busin);

                }



            }
            //权限加入
            //删除权限
            List<Xyuserrole> rolelist = xyuserroleService.queryByUserId(xyuser.getUserId());
            if (rolelist.size() > 0) {

                xyuserroleService.deleteByEntityIds(rolelist);
            }

            List<Xyuserrole> xyroleList = new ArrayList<Xyuserrole>();
            if (roleIds != null) {
                for (String roleId : roleIds) {
                    if (StringUtils.isNotBlank(roleId)) {
                        Xyuserrole xyuserrole = new Xyuserrole();
                        xyuserrole.setRoleId(roleId);
                        xyuserrole.setUserroleId(UUIDUtils.getUUID());
                        xyuserrole.setUserId(xyuser.getUserId());
                        xyroleList.add(xyuserrole);
                    }
                }
            }
            if (xyroleList.size() > 0) {
                xyuserroleService.saves(xyroleList);
            }
            //==============

            model.addAttribute("success", "保存用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存用户失败!详情："+e.getMessage());
        }
        return "redirect:list.do";
    }
    /** 保存管理员修改密码 **/
    @RequestMapping("/savepwd.do")
    public String savepwd(Xyuser xyuser,Integer iscreate,
                       HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model) {
        if(StringUtils.isNotBlank(xyuser.getUserId())&&StringUtils.isNotBlank(xyuser.getPassword())){
            Xyuser xyuser2 = xyuserService.queryById(xyuser.getUserId());
            xyuser2.setPassword(DecriptTest.SHA1(xyuser.getPassword()));
            xyuserService.update(xyuser2);
        }

        model.addAttribute("success", "保存用户成功");
        return "redirect:list.do";
    }


        /** 详情 **/
    @RequestMapping("/detail.do")
    public String detail(@RequestParam(required = true)String userId, Xyuser xyuser, HttpServletRequest req, HttpServletResponse resp,
                         ModelMap model){
        setMsg(xyuser,req,model);
        try {
            Xyuser entity = xyuserService.queryById(xyuser.getUserId());

            model.addAttribute("entity", entity);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "查询用户出错!详情："+e.getMessage());
        }
        return "xyuser/detail";
    }
    /** 新增或修改 **/
    @RequestMapping("/add.do")
    public String add(Xyuser xyuser, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(xyuser,req,model);
        setRoleList(xyuser,model);
        if(StringUtils.isNotBlank(xyuser.getUserId())){
            xyuser = xyuserService.queryById(xyuser.getUserId());
            Map<String, Object> data = ConvertObj.toMap(xyuser);
            Czjbusiness czjbusiness=czjbusinessService.getBusinessByTuserid(xyuser.getUserId());
            if(czjbusiness!=null){
                data.put("phone", czjbusiness.getPhone());
            }

            model.addAttribute("entity", data);
            

            
        }
        return "xyuser/add";
    }
    /** 删除 **/
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(required = true)String userId,Xyuser xyuser, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            xyuserService.deleteById(xyuser.getUserId());//删除用户

            Czjbusiness business = czjbusinessService.queryByUserId(xyuser.getUserId());
            if(business!=null&&business.getId()!=null){//有商家的情况下删除
                business.setDelFlag(1);
                czjbusinessService.update(business);//删除商家，假删
                czjcommodityService.updateDelByBusinessId(business.getId(),1);//把商家所有商品给下架了
            }

        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:list.do";
    }

    private void setMsg(Xyuser xyuser,HttpServletRequest req, ModelMap model) {
        model.addAttribute("failed", req.getParameter("failed"));
        model.addAttribute("success", req.getParameter("success"));
        model.addAttribute("entity", xyuser);
    }

    /** 修改密码页面 **/
    @RequestMapping("/updatepasswd.do")
    public String updatepassd(Xyuser xyuser,HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        model.addAttribute("entity",xyuser);

        return "xyuser/updatepasswd";
    }
    /** 通过原密码修改密码页面 **/
    @RequestMapping("/upd.do")
    public String upd(Xyuser xyuser,HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        model.addAttribute("entity",xyuser);
        model.addAttribute("success",req.getParameter("success"));
        model.addAttribute("failed",req.getParameter("failed"));

        return "xyuser/upd";
    }
    @RequestMapping("/saveupd.do")
    public String saveupd(Xyuser xyuser,
                          String password,String oripassword,String password2,
                          HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model){
//        model.addAttribute("entity",xyuser);
        if(!password2.equals(xyuser.getPassword())){
            model.addAttribute("failed","密码和重复密码不匹配！");
        }else {
            if (StringUtils.isNotBlank(password2)&& StringUtils.isNotBlank(xyuser.getPassword())) {


                if (xyuser.getUserId() != null && StringUtils.isNotBlank(xyuser.getUserId())) {
                    Xyuser xyuser2 = xyuserService.queryById(xyuser.getUserId());
                    if(DecriptTest.SHA1(oripassword).equals(xyuser2.getPassword())){
                        xyuser2.setPassword(DecriptTest.SHA1(password));
                        xyuserService.update(xyuser2);
                        model.addAttribute("success", "更新成功");
                        return "redirect:/admin/logout.do?userId="+xyuser2.getUserId();
                    }else{
                        model.addAttribute("success", "原输入密码不正确");
                    }



                } else {
                    model.addAttribute("failed", "更新密码不成功，用户不存在！");
                }
            } else {
                model.addAttribute("failed", "原密码、密码、重复密码不能为空");
            }
        }


        return "redirect:upd.do?userId="+xyuser.getUserId();
    }

    public void setRoleList(Xyuser xyuser, ModelMap modelMap) {
        List<Xyuserrole> xyuserrolelisst = xyuserroleService.queryByUserId(xyuser.getUserId());
        Map<String, Xyuserrole> xyuserroleMap = new HashMap<String, Xyuserrole>();
        for (Xyuserrole xyuserrole : xyuserrolelisst) {
            xyuserroleMap.put(xyuserrole.getRoleId(), xyuserrole);
        }

        List<Xyrole> rolelist = xyroleService.queryAll();
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();

        for (int i = 0; i < rolelist.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name",rolelist.get(i).getName());
            map.put("roleId",rolelist.get(i).getRoleId());
            if(xyuserroleMap.get(rolelist.get(i).getRoleId())!=null&&xyuserroleMap.get(rolelist.get(i).getRoleId()).getUserroleId()!=null){
                map.put("checked",1);
            }else{
                map.put("checked",0);
            }

            listmap.add(map);
        }
        modelMap.addAttribute("rolelist",listmap);

    }

    /** 创建用户 **/
    @RequestMapping("/iscreate.do")
    public String iscreate(@RequestParam(required = true) String userId, HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model){
        Xyuser user = xyuserService.queryById(userId);
        if(user==null){
            model.addAttribute("failed", "用户不存在！");
            return "redirect:list.do";
        }
        Czjbusiness business = czjbusinessService.queryByUserId(userId);
        if(business!=null){
            model.addAttribute("failed", "商家已存在！");
            return "redirect:list.do";
        }


        //商家创建
        Czjbusiness busin = new Czjbusiness();
        busin.setUsername(user.getUserId());
        busin.setId(UUIDUtils.getUUID());
        if(null!=user.getNickname()){
            busin.setBusinessName(user.getNickname());
        }
        czjbusinessService.insert(busin);

        model.addAttribute("success", "创建商家成功！");
        return "redirect:list.do";
    }
}
